import socket
from threading import Thread
from protocol import *
from correctortimer import CorrectorTimer
from gameengine import GameEngine

import sys
sys.path.append('./libs/')

from logger import log
from dispatcher import Dispatcher
from worker import Worker
import worker
from unit import Unit
from storage import Storage

class Server(Thread):
	def __init__(self, host, port):
		Thread.__init__(self)

		self.dispatcher = Dispatcher()
		self.gameEngine = GameEngine()

#		self.correctorTimer = CorrectorTimer(5, self.dispatcher)
#		self.correctorTimer.start()
		self.host = host
		self.port = port

		Storage()

		log('Created server')

	def printInfo(self):
		self.dispatcher.printInfo()

	def run(self):
		log('Started server')

		self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		self.server.bind((self.host, self.port))
		self.server.listen(5)
		while True:
			self.printInfo()

			client, info = self.server.accept()
			unit = Unit(self.gameEngine, self.dispatcher, client, info)
			self.dispatcher.dispatchUnit(unit)

			self.dispatcher.broadcastEvent(Packet({'a':'connected','sender':info[0]}), exclude=[unit])

		pass
